var map_id = 1;

function replaceAll(text, strA, strB) {
    return text.replace(new RegExp(strA, "g"), strB);
}


function hide(id) {
    $(id).hide();
}


function singleElement(idName, options) {
    var topicName = options.topicName;
    var currentVal = options.currentVal;
    var property = options.property;
    var propertyType = options.propertyType;
    var postCommand = "/company_info/write/";
    var useSuggest = options.useSuggest;
    var htmlName = idName;
    var formElement = $("#" + htmlName).html((currentVal ? currentVal : "") + " <em>[Edit]</em>").attr("name", "e_value=" + (currentVal ? currentVal : "") + " pid=" + property).click(function (e) {if ($(this).length > 0) {var id = $(this).get(0).id;id = id.replace(/span_/, "");if ($("#" + id).length == 0) {var text = $("<form id=\"form_" + id + "\" name=\"form_" + id + "\"><input type=\"text\" name=\"" + $("#span_" + id).attr("name") + "\" id=\"" + id + "\" />" + "<input type=\"hidden\" name=\"tid\" value=\"/en/" + topicName + "\" id=\"tid_" + id + "\"/>" + "<input type=\"hidden\" name=\"orig_val\" value=\"" + currentVal + "\" id=\"originalVal\"/>" + "<input type=\"hidden\" name=\"property\" value=\"/en/" + topicName + "\" id=\"tid_" + id + "\"/>" + "<input type=\"hidden\" name=\"id_value\" value=\"" + id + "\" id=\"id_val\"/>" + "<input type=\"submit\" id=\"submit_" + id + "\" value=\"Save\" /> <input type=\"button\" id=\"cancel_" + id + "\" value=\"Cancel\" /></form>");$(this).parent().append(text);var options = {soft: true, ac_param: {type: propertyType}};if (useSuggest) {$("#" + id).freebaseSuggest(options);}$("#" + id).val($(this).html().substring(0, $(this).html().indexOf(" <em>[Edit]</em>")));$("#submit_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;id = id.replace(/submit_/, "");$("#span_" + id).attr("name", "e_value=" + $("#" + id).val() + " pid=" + property).html($("#" + id).val() + " <em>[Edit]</em>").toggle();$("#form_" + id).toggle();$("#tabbed-container").tabs({disabled: [0, 1, 2, 3, 4]});var objects = new Object;for (var i = 0; i < $("#form_" + id + " > input").length; i++) {var o = $("#form_" + id + " > input").get(i).id;if ($("#" + o).attr("name") != "undefined" || typeof $("#" + o).attr("name") != "undefined") {if ($("#" + o).attr("type") && $("#" + o).attr("type").toLowerCase() != "button" && $("#" + o).attr("type").toLowerCase() != "submit") {var s = $("#" + o).attr("name");s = s.split(" ");for (var x in s) {if (s[x] && typeof s[x].split != "undefined") {var str = s[x].split("=");if (str.length == 2) {objects[str[0]] = str[1];}}}objects[o] = $("#" + o).attr("value");}}}$.ajax({type: "POST", url: postCommand + topicName + ("/"), data: objects, success: function (m) {perform_touch(freebase_domain);}, error: function (m) {}, dataType: "text", cache: false});return false;}});$("#cancel_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;id = id.replace(/cancel_/, "");$("#" + id).val($("#span_" + id).html().substring(0, $("#span_" + id).html().indexOf(" <em>[Edit]</em>")));$("#span_" + id).toggle();$("#form_" + id).toggle();return false;}});} else {$("#form_" + id).toggle();}$("#" + id).focus();$(this).toggle();}});
}


function blurbElement(idName, options) {
    var postCommand = "/topic_info/write_blurb/";
    var topicName = options.topicName;
    var currentVal = options.currentVal;
    var property = options.property;
    var propertyType = options.propertyType;
    var topicID = options.topic_id;
    var articleID = options.article_id;
    var pID = options.p_id;
    var domain_used = options.domain_used;
    var topic_domain = options.topic_domain;
    var topic_id = options.topic_id;
    var num_chars = options.num_chars;
    var htmlName = idName;
    var display_id = "display_" + htmlName;
    var current_val_html = "<div id=\"" + display_id + "\">" + (currentVal ? currentVal : "") + " <em>[Edit]</em></div>";
    var formElement = $("#" + htmlName);
    $("#" + htmlName).html(current_val_html);
    $("#" + display_id).attr("name", "e_value=" + (currentVal ? currentVal : "") + " pid=" + property).click(function (e) {if ($(this).length > 0) {var id = $(this).get(0).id;var parent_id = id.replace(/display_/, "");var current_blurb = $(this).html().substring(0, $(this).html().indexOf(" <em>[Edit]</em>"));$("#" + parent_id).empty();var edit_id = "edit_" + parent_id;var text = $("<form id=form_\"" + parent_id + "\"><textarea type=\"textarea\" \"style=\"width: 600px; min-height: 100px; class=\"expanding\" name=\"" + $("#" + edit_id).attr("name") + "\" id=\"" + id + "\">" + current_blurb + "</textarea>" + "<input type=\"hidden\" name=\"pid\" value=\"" + property + "\" id=\"pid\"/>" + "<input type=\"hidden\" name=\"tid\" value=\"/en/" + topicName + "\" id=\"tid_" + id + "\"/>" + "<input type=\"hidden\" name=\"orig_val\" value=\"" + currentVal + "\" id=\"originalVal\"/>" + "<input type=\"hidden\" name=\"property\" value=\"/en/" + topicName + "\" id=\"tid_" + id + "\"/>" + "<input type=\"hidden\" name=\"id_value\" value=\"" + id + "\" id=\"id_val\"/>" + "<br></br><input type=\"submit\" id=\"submit_" + parent_id + "\" value=\"Save\" /> <input type=\"button\" id=\"cancel_" + parent_id + "\" value=\"Cancel\" /></textarea>");$("#" + parent_id).append(text);$("#" + edit_id).val(current_blurb);$("#submit_" + parent_id).bind("click", function (e, data) {if ($(this).length > 0) {$("#tabbed-container").tabs({disabled: [0, 1, 2, 3, 4]});createSyncButton(topicName);var id = $(this).get(0).id;id = id.replace(/submit_/, "");var objects = new Object;objects.e_value = $("#display_" + id).val();objects.article_id = articleID;objects.topic_id = topicID;objects.p_id = pID;$("#" + id).empty();$.ajax({type: "POST", async: false, url: postCommand + topicName + ("/"), data: objects, success: function (m) {}, error: function (m) {var test = 0;test = 0;}, dataType: "text", cache: false});perform_touch(domain_used);createBlurbElement(domain_used, topicName, topic_domain, topic_id, num_chars, idName);return false;}});$("#cancel_" + parent_id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;id = id.replace(/cancel_/, "");$("#" + id).empty();blurbElement(idName, options);return false;}});$("#" + id).focus();$(this).toggle();return false;}});
}


function createBlurbElement(domain_used, name, topic_domain, topic_id, num_chars, html_id) {

    var overview_options = {
        topicName: name,
        currentVal: "",
        topic_id: topic_id,
        article_id: "n/a",
        p_id: "/topic/overview",
        domain_used: domain_used,
        topic_domain: topic_domain,
        topic_id: topic_id,
        num_chars: num_chars
    };

    jsonp_totalblurb_freebase(
        domain_used, name, topic_domain, 500,
        function (m) {},
        function (m) {
            overview_options.currentVal = m.result.body;
            overview_options.article_id = m.article_id;
            blurbElement(html_id, overview_options);
        },
        function (m) {var test = 0;}
    );
    
    blurbElement(html_id, overview_options);
}


function multiElement(idName, options, domain_used) {
    var topicName = options.topic_name;
    var currentVals = options.current_vals;
    var property = options.property;
    var topic_type = options.type;
    var propertyType = options.property_type;
    var postCommand = "/topic_info/write_multi/";
    var html_id = idName;
    var display_id = "display_" + html_id;
    var currentValHtml = "<div id=\"" + display_id + "\">";
    for (var i = 0; i < currentVals.length; i++) {
        currentValHtml += currentVals[i].name;
        currentValHtml += i < currentVals.length - 1 ? "; " : "";
    }
    currentValHtml += "<em>[Edit]</em></div>";
    arrLength = currentVals.length;
    var addArray = [];
    var addArray2 = [];
    $("#" + html_id).html(currentValHtml);
    $("#" + display_id).click(function (e) {if ($(this).length > 0) {var id = html_id;var parentElement = $("#" + html_id);parentElement.empty();var textTemp = generateArrayEdit(id, topicName, currentVals, property, propertyType, parentElement);$("#" + id).val($(this).html().substring(0, $(this).html().indexOf(" <em>[Edit]</em>")));$("#add_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;var id_full = id.replace(/add_/, "");onAddMulti(id_full, propertyType);}});$("#submit_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;$("#tabbed-container").tabs({disabled: [0, 1, 2, 3, 4]});onSubmitMulti(id, options, domain_used);createSyncButton(topicName);}return false;});$("#cancel_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;onCancelMulti(id, options);}});$("#" + id).focus();}});
}


function onSubmitMulti(id, options, domain_used) {
    var topicName = options.topic_name;
    var currentVals = options.current_vals;
    var property = options.property;
    var topic_type = options.topic_type;
    var propertyType = options.property_type;
    var origVal_ids = options.element_id;
    var currentValsNew = Array();
    var topic_id = options.topic_id;
    var vals_id_prefix = options.vals_id_prefix;
    var postCommand = "/topic_info/write_multi/";
    var full_id = id.replace(/submit_/, "");
    var siblings = null;
    if (typeof vals_id_prefix != "undefined") {
        var siblings = $("#" + vals_id_prefix + full_id).children();
    } else {
        var siblings = $("#" + id).siblings();
    }
    var newVals = [];
    var newIDs = [];
    var newTopicBools = [];
    var newValIndex = 0;
    for (var i = 0; i < siblings.length; i++) {
        var sib = siblings[i];
        if (sib.type == "text" && sib.value.length > 0) {
            newVals.push(sib.value);
            newIDs.push(sib.attributes.guid.value);
            newTopicBools.push(sib.attributes.create_new.value);
            newValIndex++;
        }
    }
    var vals_to_add = Object();
    vals_to_add.data = Array();
    var currents_found = Array();
    for (var a = 0; a < currentVals.length; a++) {
        currents_found[a] = false;
    }
    for (var i = 0; i < newVals.length; i++) {
        var newVal = newVals[i];
        var isfound = false;
        for (var j = 0; j < currentVals.length; j++) {
            if (newVal == currentVals[j].name) {
                isfound = true;
                currents_found[j] = true;
            }
        }
        if (!isfound) {
            var add_index = vals_to_add.data.length;
            vals_to_add.data[add_index] = Object();
            vals_to_add.data[add_index].val = newVal;
            vals_to_add.data[add_index].id = newIDs[i];
            vals_to_add.data[add_index].create_new = newTopicBools[i];
        }
    }
    var vals_to_remove = Object();
    vals_to_remove.data = Array();
    for (var i = 0; i < currents_found.length; i++) {
        if (!currents_found[i]) {
            var remove_index = vals_to_remove.data.length;
            vals_to_remove.data[remove_index] = Object();
            vals_to_remove.data[remove_index].val = currentVals[i].name;
            vals_to_remove.data[remove_index].id = currentVals[i].guid;
        }
    }
    var propertyTypeCreateString = "[";
    for (var a = 0; a < propertyType.length; a++) {
        propertyTypeCreateString += "\"" + propertyType[a] + "\"";
        propertyTypeCreateString += a < propertyType.length - 1 ? "," : "";
    }
    propertyTypeCreateString += "]";
    var newValsStringHTML = newVals.join(";");
    var vals_to_add_string = JSON.stringify(vals_to_add);
    var vals_to_remove_string = JSON.stringify(vals_to_remove);
    var topic1 = new Object;
    topic1.id = topic_id;
    topic1.property = property;
    var topic2 = new Object;
    topic2.type = propertyType;
    topic2.type_for_create = propertyTypeCreateString;
    topic2.topics_to_add = vals_to_add;
    topic2.topics_to_remove = vals_to_remove;
    var objects = new Object;
    objects.topic1 = JSON.stringify(topic1);
    objects.topic2 = JSON.stringify(topic2);
    $("#" + full_id).empty();
    perform_touch(domain_used);
    $.ajax({type: "POST", url: postCommand + "write_multi/", data: objects, async: false, success: function (m) {}, error: function (m) {}, dataType: "text", cache: false});
    perform_touch(domain_used);
    perform_freebase_read(options.url_read, options.current_vals_q, function (msg) {var new_vals = msg.result && msg.result[0] ? msg.result[0] : null;var new_options = options;new_options.current_vals = new_vals[options.property];multiElement(full_id, new_options, domain_used);}, function (m) {});
    return false;
}


function generateArrayEdit(id, topicName, currentVals, property, propertyType, parentElement) {
    var textTemp = "<form id=\"form_" + id + "\" name=\"form_" + id + "\" >";
    textTemp += multiArrayRowHTML(currentVals, id);
    textTemp += "<input type=\"hidden\" name=\"pid\" value=\"" + property + "\" id=\"pid_" + id + "\"></input>";
    textTemp += "<input type=\"hidden\" name=\"property\" value=\"/en/" + topicName + "\" id=\"tid_" + id + "\"></input>";
    textTemp += "<input type=\"hidden\" name=\"array_length\" value=\"" + currentVals.length + "\" id=\"len_orig\"></input>";
    textTemp += "<input type=\"hidden\" name=\"id_value\" value=\"" + id + "\" id=\"id_val\"></input>";
    textTemp += "<input type=\"button\" id=\"add_" + id + "\" value=\"+\"></input>" + "<input type=\"submit\" id=\"submit_" + id + "\" value=\"Save\"></input>" + "<input type=\"button\" id=\"cancel_" + id + "\" value=\"Cancel\"></input></form>";
    parentElement.append($(textTemp));
    fbSuggestMultiRow(id, currentVals, propertyType);
    onAddMulti(id, propertyType);
}


function multiArrayRowHTML(currentVals, id) {
    var s = "";
    for (var i = 0; i < currentVals.length; i++) {
        var id_full = id + ("_" + i);
        s += "<div  id=\"tooltip" + id_full + "\" class=\"balloon\" onclick=\"hide(this)\"  >Either select a choice,<br /> or click<br /> <div style=\"\" class=\"fbs-selectnew fbs-selectnew-selected\">Create new topic</div></div><input type=\"text\" name=\"" + id_full + "\" value=\"" + currentVals[i].name + "\" id=\"" + id_full + "\"" + "guid=\"" + currentVals[i].id + "\"\" create_new=\"false\"></input>";
    }
    return s;
}


function onAddMulti(id, propertyType) {
    if ($(this).length > 0) {
        var currentValsNew = Array();
        var siblings = $("#form_" + id).children();
        var newID = id + ("_" + siblings.length - 7);
        var anotherTest = jQuery("<div  id=\"tooltip" + newID + "\" class=\"balloon\" onclick=\"hide(this)\"  >Either select a choice,<br /> or click<br /> <div style=\"\" class=\"fbs-selectnew fbs-selectnew-selected\">Create new topic</div></div><input type=\"text\" name=\"" + newID + "\" value=\"\" id=\"" + newID + "\" create_new=\"false\" style=\"float:inherit\" data_val=\"\"></input> ");
        var entry = $(siblings[siblings.length - 4]);
        entry.after(anotherTest);
        fbSuggestMulti(newID, propertyType, "Create new topic");
    }
}


function mt_onAddMulti(id, propertyType) {
    var currentValsNew = Array();
    var siblings = $("#vals_" + id).children();
    var newID = id + ("_" + siblings.length);
    var new_entry = jQuery("<input type=\"text\" name=\"" + newID + "\" value=\"\" id=\"" + newID + "\" create_new=\"false\"></input>");
    if (siblings.length > 0) {
        var entry = $(siblings[siblings.length - 1]);
        entry.after(new_entry);
    } else {
        new_entry.appendTo($("#vals_" + id));
    }
    fbSuggestMulti(newID, propertyType, "Create new topic");
}


function onCancelMulti(cancel_id, options) {
    if ($(this).length > 0) {
        var id = cancel_id.replace(/cancel_/, "");
        $("#" + id).empty();
        multiElement(id, options);
        return false;
    }
}


function compoundElement(idName, options, domain_used, flag) {
    var topicName = options.topicName;
    var name = topicName;
    name = replaceAll(name, " ", "-");
    name = name.replace(" ", "-");
    name = name.replace(".", "");
    name = name.replace(",", "");
    name = name.replace("&amp;", "");
    name = name.replace("'", "");
    var topicType = options.topic_type;
    var current_vals = options.current_vals;
    var propertyNames = options.propertyNames;
    var propertyTypes = options.propertyTypes;
    var type = options.type;
    var postCommand = "/topic_info/write_multi/";
    var parent_topic_id = options.topic_id;
    var compoundPropertyType = options.compoundPropertyType;
    var compoundProperty = options.compoundProperty;
    var useSuggest = options.useSuggest;
    var html_id = idName;
    var display_id = "display_" + html_id;
    var currentValHtml = "<div id=\"" + display_id + "\">";
    currentValHtml += createStringFromJSON_compound(current_vals, propertyNames);
    currentValHtml += "<em>[Edit]</em></div>";
    var valsArray = Object();
    valsArray.names = Array();
    valsArray.ids = Array();
    $("#" + html_id).html((currentValHtml ? currentValHtml : "") + " <em>[Edit]</em>");
    arrLength = current_vals.length;
    var addArray = [];
    var addArray2 = [];
    if (!flag) {
        $("#" + html_id).html(currentValHtml);
        $("#" + display_id).click(function (e) {if ($(this).length > 0) {$("#" + html_id).empty();var id = html_id;var parentElement = $("#" + html_id);var textTemp = generateCompoundArrayEdit(id, current_vals, propertyNames, propertyTypes, useSuggest, parentElement, valsArray);onAddCompoundRow(id, propertyNames, propertyTypes, useSuggest, null, valsArray);$("#" + id).val($(this).html().substring(0, $(this).html().indexOf("<em>[Edit]</em>")));$("#add_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;onAddCompoundRow(id, propertyNames, propertyTypes, useSuggest, null, valsArray);}});$("#submit_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;$("#tabbed-container").tabs({disabled: [0, 1, 2, 3, 4]});document.body.style.cursor = "wait";onSubmitCompound(parent_topic_id, id, options, current_vals, type, propertyNames, propertyTypes, compoundPropertyType, compoundProperty, domain_used);createSyncButton(topicName);}return false;});$("#cancel_" + id).bind("click", function (e, data) {$("#" + html_id).css({overflow: "hidden"});if ($(this).length > 0) {var id = $(this).get(0).id;onCancelCompound(id, options);}});}});
    }
    if (flag == "save") {
        $("#" + html_id).html(currentValHtml);
        $("#" + display_id).click(function (e) {if ($(this).length > 0) {$("#" + html_id).empty();var id = html_id;var parentElement = $("#" + html_id);var textTemp = generateCompoundArrayEdit(id, current_vals, propertyNames, propertyTypes, useSuggest, parentElement, valsArray, true);onAddCompoundRow(id, propertyNames, propertyTypes, useSuggest, null, valsArray, flag);$("#" + id).val($(this).html().substring(0, $(this).html().indexOf("<em>[Edit]</em>")));$("#add_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;onAddCompoundRow(id, propertyNames, propertyTypes, useSuggest, null, valsArray);}});$("#submit_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;document.body.style.cursor = "wait";onSubmitCompound(parent_topic_id, id, options, current_vals, type, propertyNames, propertyTypes, compoundPropertyType, compoundProperty, domain_used, flag);createSyncButton(topicName);}return false;});}});
    }
    if (flag && flag != "save") {
        $("#" + html_id).html(currentValHtml);
        $("#" + html_id).empty();
        var id = html_id;
        var parentElement = $("#" + html_id);
        var textTemp = generateCompoundArrayEdit(id, current_vals, propertyNames, propertyTypes, useSuggest, parentElement, valsArray, flag);
        onAddCompoundRow(id, propertyNames, propertyTypes, useSuggest, null, valsArray);
        $("#" + id).val($("#" + html_id).html().substring(0, $("#" + html_id).html().indexOf("<em>[Edit]</em>")));
        $("#submit_" + id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;var parent_id = id.replace("submit_", "");$("#" + parent_id).fadeOut(1000, function () {document.body.style.cursor = "wait";onSubmitCompound(parent_topic_id, id, options, current_vals, type, propertyNames, propertyTypes, compoundPropertyType, compoundProperty, domain_used, flag);createSyncButton(topicName);});}return false;});
    }
}


function createStringFromJSON_compound(vals, propertyNames) {
    var s = "<table><thead><tr>";
    for (var a = 0; a < propertyNames.length; a++) {
        s += "<th>" + propertyNames[a] + "</th>";
    }
    s += "</tr></thead>";
    for (var i = 0; i < vals.length; i++) {
        var v = vals[i];
        s += "<tr>";
        for (var a = 0; a < propertyNames.length; a++) {
            var v_data_temp = v[propertyNames[a]];
            s += "<td>";
            if (v_data_temp != null) {
                var v_data = v_data_temp.name;
                if (typeof v_data != "undefined") {
                    if (v_data != null) {
                        s += "<input type=\"text\" disabled=\"disabled\" id=\"" + propertyNames[a] + "\" value=\"" + v_data + "\"/>";
                    } else {
                        s += "<input type=\"text\" disabled=\"disabled\" id=\"" + propertyNames[a] + "\" value=\"\"/>";
                    }
                } else {
                    s += "<input type=\"text\" disabled=\"disabled\" id=\"" + propertyNames[a] + "\" value=\"" + v_data_temp + "\"/>";
                }
            } else {
                s += "<input type=\"text\" disabled=\"disabled\" id=\"" + propertyNames[a] + "\" value=\"\"/>";
            }
            s += "</td>";
        }
        s += "</tr>";
    }
    s += "</table>";
    return s;
}


function onSubmitCompound(parent_topic_id, id, options, current_vals, topicType, propertyNames, propertyTypes, compoundPropertyType, compoundProperty, domain_used, flag) {
    if ($(this).length > 0) {
        var parent_id = id.replace("submit_", "");
        var name = options.topicName;
        name = replaceAll(name, " ", "-");
        name = name.replace(" ", "-");
        name = name.replace(".", "");
        name = name.replace(",", "");
        name = name.replace("&amp;", "");
        name = name.replace("'", "");
        var form = $("#form_" + parent_id);
        var rows = form.children().children().children().siblings();
        var vals_to_add = new Array;
        var vals_to_remove = new Array;
        var newValsHTML = "";
        var topic1_vals = Object();
        topic1_vals.data = Array();
        topic1_vals.type = compoundPropertyType;
        var topic2_vals = Object();
        topic2_vals.data = Array();
        for (var i = 0; i < rows.length - 1; i++) {
            var row_index = i + 1;
            var row_val = getElementParameters_html($("#row_" + row_index + "_" + parent_id));
            var add_new_compound_row = row_val.create_new.toLowerCase() == "true";
            var row_object = null;
            if (add_new_compound_row) {
                row_object = new Object;
                row_object.type = "link";
                row_object.topic1 = new Object;
                row_object.topic1.guid = parent_topic_id;
                row_object.topic2 = new Array;
                row_object.topic2[0] = row_val;
                row_object.topic2[0].elements_to_add = new Array;
                row_object.topic2[0].topic1_property = compoundProperty;
                row_object.topic2[0].type = compoundPropertyType;
                row_object.topic2[0].force_create = "true";
            }
            var add_element_index = 0;
            var val_to_add = new Object;
            val_to_add.type = "link";
            val_to_add.topic1 = new Object;
            val_to_add.topic1.guid = row_val.guid;
            val_to_add.topic2 = new Array;
            var current_vals_row = i < current_vals.length ? current_vals[i] : null;
            var row = rows[i];
            var elements = row.cells;
            for (var j = 0; j < elements.length; j++) {
                var element_id = "#" + parent_id + "_" + i + 1 + "_" + j;
                var element = getElementParameters_html($(element_id));
                if (isPrimativeType(propertyTypes[j])) {
                    element.name = $(element_id).val();
                }
                var add_element = false;
                var remove_element = false;
                if (element.create_new.toLowerCase() == "true") {
                    add_element = true;
                } else {
                    var current_comp_element = current_vals_row != null ? current_vals_row[propertyNames[j]] : null;
                    if (current_comp_element == null) {
                        if (element.name.length > 0) {
                            add_element = true;
                        }
                    } else {
                        if (isPrimativeType(propertyTypes[j])) {
                            var current_val_temp = current_comp_element.length > 0 ? current_comp_element[0] : current_comp_element;
                            if (!(current_val_temp == element.name)) {
                                add_element = true;
                            }
                        } else {
                            if (!(current_comp_element.guid == element.guid)) {
                                remove_element = true;
                                add_element = true;
                            }
                        }
                    }
                }
                if (add_element) {
                    var topic2 = val_to_add.topic2;
                    topic2[add_element_index] = new Object;
                    val_to_add.topic2[add_element_index] = element;
                    val_to_add.topic2[add_element_index].topic1_property = compoundPropertyType.replace(/"/g, "") + ("/" + propertyNames[j]);
                    val_to_add.topic2[add_element_index].type = element.type;
                    val_to_add.topic2[add_element_index].elements_to_add = new Array;
                    val_to_add.topic2[add_element_index].force_create = "false";
                    add_element_index++;
                }
                if (remove_element &&
                    typeof compound_row != "undefined") {
                    var remove_element_index = 0;
                    var val_to_remove = new Object;
                    val_to_remove.type = "unlink";
                    val_to_remove.topic1 = new Object;
                    val_to_remove.topic1.guid = compound_row.guid;
                    val_to_remove.topic2 = new Object;
                    val_to_remove.topic2.guid = current_comp_element_guid;
                    val_to_remove.topic2.topic1_property = structure_element.topic1_property_full;
                    val_to_remove.topic2.type = comp_element_topic_type;
                    vals_to_remove.push(val_to_remove);
                }
            }
            if (add_new_compound_row) {
                if (val_to_add.topic2.length > 0) {
                    row_object.topic2[0].elements_to_add.push(val_to_add);
                    vals_to_add.push(row_object);
                }
            } else {
                if (val_to_add.topic2.length > 0) {
                    vals_to_add.push(val_to_add);
                }
            }
        }
        var post_command = "/topic_info/write_mixed/";
        $("#" + parent_id).empty();
        perform_touch(domain_used);
        if (vals_to_add.length > 0 || vals_to_remove.length > 0) {
            var transmit_data = new Object;
            transmit_data.vals_to_add = JSON.stringify(vals_to_add);
            transmit_data.vals_to_remove = JSON.stringify(vals_to_remove);
            $.ajax({type: "POST", async: false, url: post_command + parent_id + ("/"), data: transmit_data, success: function (m) {}, error: function (xhr, desc, exceptionobj) {}, dataType: "text", cache: false});
        }
        perform_touch(domain_used);
        perform_freebase_read(options.url_read, options.current_vals_q, function (msg) {var new_vals = msg.result && msg.result[0] ? msg.result[0] : null;var new_options = options;new_options.current_vals = new_vals[options.compoundProperty];if (flag) {compoundElement(parent_id, new_options, domain_used, "save");$("#" + parent_id).show();var street = $("#street_address").val();var city = $("#citytown").val();var state = $("#state_province_region").val();var postal_code = $("#postal_code").val();var address = "";if (typeof street != "undefined" && street != "") {address += street + ",";}if (typeof city != "undefined" && city != "") {address += city + ",";}if (typeof state != "undefined" && state != "") {address += state + ",";}if (typeof postal_code != "undefined" && postal_code != "") {address += postal_code;}if (address != "") {if (GBrowserIsCompatible()) {map = new GMap2(document.getElementById("map_canvas_1"));geocoder = new GClientGeocoder;geocoder.getLatLng(address, function (point) {if (!point) {alert(address + " not found");} else {point_val = point;map.setCenter(point, 13);marker = new GMarker(point, {draggable: true});map.addOverlay(marker);}});map.enableScrollWheelZoom();}$("#submit_" + name).removeAttr("disabled");}} else {compoundElement(parent_id, new_options, domain_used);}}, function (m) {});
    }
    document.body.style.cursor = "default";
}


function onCancelCompound(id, options) {
    if ($(this).length > 0) {
        id = id.replace(/cancel_/, "");
        $("#" + id).empty();
        compoundElement(id, options);
        return false;
    }
}


function generateCompoundArrayEdit(html_id, vals, property_names, property_types, use_suggest, parent_element, val_arrays, flag) {
    var textTemp = "<form id=\"form_" + html_id + "\" name=\"form_" + html_id + "\" >";
    textTemp += "<table>";
    textTemp += createPropertyRow(property_names);
    textTemp += "</table>";
    textTemp += "</form>";
    parent_element.append($(textTemp));
    if (flag) {
        $("#" + html_id).css({width: "800px"});
    } else {
        $("#" + html_id).css({width: "650px"});
        $("#" + html_id).css({overflow: "auto"});
    }
    for (var i = 0; i < vals.length; i++) {
        var v = vals[i];
        val_arrays = onAddCompoundRow(html_id, property_names, property_types, use_suggest, v, val_arrays);
    }
    var form = $("#form_" + html_id);
    var table = form.children();
    if (flag) {
        var buttons = "<input type=\"submit\" id=\"submit_" + html_id + "\" value=\"Save and verify location on map\" />" + "</form><div id=\"popup" + html_id + "\" style=\"display:none\"> </div>";
    } else {
        var buttons = "<input type=\"button\" id=\"add_" + html_id + "\" value=\"+\"/>" + "<input type=\"submit\" id=\"submit_" + html_id + "\" value=\"Save\" />" + "<input type=\"button\" id=\"cancel_" + html_id + "\" value=\"Cancel\" /></form><div id=\"popup" + html_id + "\" style=\"display:none\"> </div>";
    }
    table.after($(buttons));
}


function createPropertyRow(property_names) {
    var s = "<thead><tr>";
    for (var a = 0; a < property_names.length; a++) {
        s += "<th>" + property_names[a] + "</th>";
    }
    s += "</tr></thead>";
    return s;
}


function onAddCompoundRow(html_id, property_names, property_types, use_suggest, row_vals, vals_array, flag) {
    if (!flag) {
        var create_new_row = false;
        if (row_vals == null) {
            create_new_row = true;
            row_vals = Object();
            for (var a = 0; a < property_names.length; a++) {
                row_vals[property_names[a]] = null;
            }
        }
        var siblings = $("#" + html_id).siblings();
        html_id = html_id.replace(/add_/, "");
        var form = $("#form_" + html_id);
        var rows = form.children().children().children();
        var newID = "row_" + html_id + "_" + rows.length;
        var rowNum = rows.length;
        var rowText = createCompoundRow(html_id, row_vals, property_names, property_types, rowNum, create_new_row);
        var anotherRow = jQuery(rowText);
        var lastRow = $(rows[rows.length - 1]);
        lastRow.after(anotherRow);
        fbSuggestCompoundRow(html_id, property_types, use_suggest, rowNum, row_vals.id);
    } else {
        var create_new_row = false;
        if (row_vals == null) {
            create_new_row = true;
            row_vals = Object();
            for (var a = 0; a < property_names.length; a++) {
                row_vals[property_names[a]] = null;
            }
        }
        var siblings = $("#" + html_id).siblings();
        html_id = html_id.replace(/add_/, "");
        var form = $("#form_" + html_id);
        var rows = form.children().children().children();
        var newID = "row_" + html_id + "_" + rows.length;
        var rowNum = rows.length;
        var rowText = createCompoundRow(html_id, row_vals, property_names, property_types, rowNum, create_new_row, flag);
        var anotherRow = jQuery(rowText);
        var lastRow = $(rows[rows.length - 1]);
        lastRow.after(anotherRow);
        fbSuggestCompoundRow(html_id, property_types, use_suggest, rowNum, row_vals.id);
    }
}


function createCompoundRow(html_id, v, property_names, property_types, row_num, create_new_row, flag) {
    var row_html_id = "row_" + row_num + "_" + html_id;
    var row_html_params = create_new_row ? createHTMLParamsEmpty(row_html_id) : createHTMLParams(row_html_id, v.guid, v.id, "", v.type, false);
    var s = "<tr " + row_html_params + " >";
    if (!flag) {
        for (var a = 0; a < property_names.length; a++) {
            var v_data = v[property_names[a]];
            var property_type = property_types[a];
            var html_id_full = html_id + ("_" + row_num + "_" + a);
            var topic_name = "";
            var data_id = "";
            var data_guid = "";
            if (isPrimativeType(property_type)) {
                topic_name = v_data != null ? v_data : "";
                data_id = "n/a";
                data_guid = "n/a";
            } else {
                if (v_data == null || typeof v_data == "undefined") {
                    v_data = Object();
                    v_data.name = "";
                    v_data.id = "";
                    v_data.guid = "";
                }
                topic_name = v_data.name != null || v_data.name == "undefined" ? v_data.name : "";
                data_id = v_data.id;
                data_guid = v_data.guid;
            }
            s += "<td>";
            s += "<input type=\"text\"";
            s += createHTMLParams(html_id_full, data_guid, data_id, topic_name, property_type, false);
            s += "></input>";
            s += "</td>";
        }
    } else {
    }
    s += "</tr>";
    return s;
}


function fbSuggestCompoundRow(id, property_types, use_suggest, row_num, topic1_id) {
    var suggestNewText = "Create new topic";
    for (var a = 0; a < property_types.length; a++) {
        var propertyType = property_types[a];
        if (propertyType != null && use_suggest[a]) {
            var id_full = id + ("_" + row_num + "_" + a);
            var options2 = {soft: true, suggest_new: suggestNewText, ac_param: {type: propertyType}};
            $("#" + id_full).freebaseSuggest(options2).bind("fb-select", function (e, data) {$(this).attr("create_new", "false");$(this).attr("guid", data.id);$(this).attr("topic_guid", data.id);$(this).attr("topic_name", data.id);$(this).attr("value", data.name);}).bind("fb-select-new", function (e, data) {$("#" + id_full).attr("create_new", "true");$("#" + id_full).attr("guid", "n/a");$("#" + id_full).attr("topic_guid", "n/a");$("#" + id_full).attr("topic_name", $("#" + id_full).val());});
        }
    }
}


function mixedElement(html_id, data, parent_element) {
    var parent_name = data.topic_name;
    var parent_id = data.topic_id;
    var parent_type = data.topic_type;
    var current_vals = data.current_vals;
    var parent_property = data.property;
    var element_structure = data.element_structure;
    var edit_blurb = data.edit_blurb;
    var display_id = "display_" + html_id;
    var display_html = "<input type=\"button\" id=\"" + display_id + "\" value=\"Edit " + parent_name + "'s " + edit_blurb + "\"/>";
    var is_expanded = false;
    var htmlName = html_id;
    var valsArray = Object();
    valsArray.names = Array();
    valsArray.ids = Array();
    generateMixedElement(html_id, data, $("#" + html_id), disable = true);
    $("#" + html_id).append(display_html);
    $("#" + display_id).click(function (e) {if (!is_expanded) {if ($(this).length > 0) {var id = $(this).get(0).id;id = id.replace(/span_/, "");var parent_element = $(this).parent();parent_element.html("");generateMixedElement(html_id, data, parent_element, disable = false);$("#" + id).focus();$(this).toggle();is_expanded = true;}}});
}


function generateMixedElement(html_id, data_options, parent_element, disable) {
    var parent_name = data_options.topic_name;
    var element_structure = data_options.element_structure;
    var current_vals = data_options.current_vals;
    var topic1_type = element_structure.topic1_type;
    var topic2 = element_structure.topic2;
    var textTemp = "<form id=\"form_" + html_id + "\" name=\"form_" + html_id + "\" >";
    textTemp += "<table id=\"table_" + html_id + ">";
    textTemp += createPropertyRow_MixedElement(element_structure);
    textTemp += "</table>";
    textTemp += "</form>";
    parent_element.append($(textTemp));
    var table = $("#table_" + html_id);
    var table_rows = table.children();
    for (var i = 0; i < current_vals.length; i++) {
        var v = current_vals[i];
        var row_id = html_id + ("_" + "row_" + i);
        var new_row = "<tr id=\"" + row_id + "\"></tr>";
        table_rows.append($(new_row));
        var primary_id = row_id + "_primary";
        var current_row = $("#" + row_id);
        primary_val = "<td>";
        primary_val += "<input type=\"text\" topic_name=\"" + v.name + "\" topic_type=\"" + v.type + "\" value=\"" + v.name + "\" id=\"" + primary_id + "\"" + "topic_guid=\"" + v.guid + "\" topic_id=\"" + v.id + "\" create_new=\"false\"></input>";
        primary_val += "</td>";
        current_row.append($(primary_val));
        $("#" + primary_id).attr("disabled", "disabled");
        for (var j = 0; j < topic2.length; j++) {
            var topic2_data = topic2[j];
            if (topic2_data.element_type == "compound") {
                createCompoundMixedElement(row_id, j, current_row, v, element_structure, v.name, disable);
            } else if (topic2_data.element_type == "overview_text") {
                var test = 0;
                createOverviewTextMixedElement(row_id, j, current_row, [], element_structure, v.name, disable);
            }
        }
    }
    if (!disable) {
        var form = $("#form_" + html_id);
        var table = form.children();
        var buttons = "<input type=\"button\" id=\"add_" + html_id + "\" value=\"" + element_structure.button_add_string + "\"/>" + "<input type=\"submit\" id=\"submit_" + html_id + "\" value=\"Save\" />" + "<input type=\"button\" id=\"cancel_" + html_id + "\" value=\"Cancel\" /></form>";
        table.after($(buttons));
        $("#add_" + html_id).bind("click", function (e, data) {if ($(this).length > 0) {var html_id = $(this).get(0).id;html_id = html_id.replace(/add_/, "");addMixedElementRow(html_id, parent_name, element_structure, parent_element);}});
        $("#submit_" + html_id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;id = id.replace(/submit_/, "");$("#tabbed-container").tabs({disabled: [0, 1, 2, 3, 4]});submitMixedElement(html_id, data_options, parent_element);$("#form_" + id).remove();mixedElement(html_id, data_options, parent_element);$("#" + id).toggle();createSyncButton(parent_name);$("#edit_" + id).attr("disabled", "disabled");}return false;});
        $("#cancel_" + html_id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;id = id.replace(/cancel_/, "");$("#form_" + id).remove();mixedElement(html_id, data_options, parent_element);$("#" + id).toggle();}});
    }
}


function addMixedElementRow(html_id, parent_name, element_structure, parent_element) {
    var topic1_type = element_structure.topic1_type;
    var topic2 = element_structure.topic2;
    var table = $("#table_" + html_id);
    var table_rows = table.children();
    var more_elements = true;
    var last_known_element = 0;
    while (more_elements) {
        var row = $("#" + html_id + "_row_" + last_known_element);
        if (row.length == 0) {
            more_elements = false;
        } else {
            last_known_element++;
        }
    }
    var row_id = html_id + ("_" + "row_" + last_known_element);
    var new_row = "<tr id=\"" + row_id + "\"></tr>";
    table_rows.append($(new_row));
    var primary_id = row_id + "_primary";
    var current_row = $("#" + row_id);
    var primary_val = "<td><input type=\"text\"" + createHTMLParams(primary_id, "", "", "", "", false) + "</input></td>";
    current_row.append($(primary_val));
    fbSuggestMulti(primary_id, topic1_type, "Create new topic.");
    for (var j = 0; j < topic2.length; j++) {
        var topic2_data = topic2[j];
        if (topic2_data.element_type == "compound") {
            createCompoundMixedElement(row_id, j, current_row, [], element_structure, "");
        } else if (topic2_data.element_type == "overview_text") {
            var test = 0;
            createOverviewTextMixedElement(row_id, j, current_row, [], element_structure, "");
        }
    }
}


function createCompoundMixedElement(row_id, col_index, current_row, current_val, element_structure, parent_name, disable) {
    var compound_table_id = row_id + ("_col_" + col_index);
    var compound_table_html = "<table id=\"" + compound_table_id + "\"></table>";
    current_row.append($(compound_table_html));
    var compound_table = $("#" + compound_table_id);
    var topic2_data = element_structure.topic2[col_index];
    var compound_datas = typeof current_val[topic2_data.topic1_property] != "undefined" ? current_val[topic2_data.topic1_property] : [];
    var data_added = false;
    for (var k = 0; k < compound_datas.length; k++) {
        data_added = true;
        var compound_row_id = compound_table_id + ("_row_" + k);
        var compound_data = compound_datas[k];
        var compound_row_html = "<tr " + createHTMLParams(compound_row_id, compound_data.guid, compound_data.id, compound_data.name, "", false) + "element_num=\"" + k + "\"></tr>";
        compound_table.append($(compound_row_html));
        var compound_row = $("#" + compound_row_id);
        var compound_element_types = topic2_data.elements;
        for (var h = 0; h < compound_element_types.length; h++) {
            var element_type = compound_element_types[h];
            if (!element_type.is_topic1) {
                var compound_element = compound_data[element_type.topic1_property];
                var compound_type = element_type.type;
                var compound_element_id = compound_row_id + ("_col_" + h);
                if (!disable) {
                    var compound_element_html = "<td><input type=\"text\"";
                } else {
                    var compound_element_html = "<td><input disabled=\"disabled\" type=\"text\" id=\"" + compound_element_id + "\"";
                }
                if (compound_element != null) {
                    compound_element_html += createHTMLParams(compound_element_id, compound_element.guid, compound_element.id, compound_element.name, "", false);
                } else {
                    compound_element_html += createHTMLParamsEmpty(compound_element_id);
                }
                compound_element_html += "></input></td>";
                compound_row.append($(compound_element_html));
                fbSuggestMulti(compound_element_id, compound_type, "Create new topic.");
            }
        }
    }
    if (!data_added) {
        addMixedCompoundRow(compound_table_id, current_val, element_structure, k);
    }
    if (!disable) {
        var buttons = "<input type=\"button\" id=\"add_" + compound_table_id + "\" element_num=\"" + col_index + "\" value=\"" + topic2_data.button_add_string + " for " + parent_name + "\"/>";
        compound_table.append($(buttons));
        $("#add_" + compound_table_id).bind("click", function (e, data) {if ($(this).length > 0) {var id = $(this).get(0).id;id = id.replace(/add_/, "");var element_num = parseFloat(this.getAttribute("element_num"));addMixedCompoundRow(id, current_val, element_structure, element_num);}});
    }
}


function createOverviewTextMixedElement(row_id, col_index, current_row, current_val, element_structure, parent_name) {
    var test = 0;
}


function addMixedCompoundRow(compound_table_id, topic1, element_structure, element_index) {
    var compound_table = $("#" + compound_table_id);
    var table_id = compound_table.attr("id");
    var topic2_data = element_structure.topic2[element_index];
    var more_elements = true;
    var last_known_element = 0;
    while (more_elements) {
        var row_id = table_id + ("_row_" + last_known_element);
        var row = $("#" + row_id);
        if (row.length == 0) {
            more_elements = false;
        } else {
            last_known_element++;
        }
    }
    var row_id = table_id + ("_row_" + last_known_element);
    var compound_row_html = "<tr " + createHTMLParamsEmpty(row_id) + "></tr>";
    compound_table.append($(compound_row_html));
    var compound_row = $("#" + row_id);
    var compound_element_types = topic2_data.elements;
    for (var h = 0; h < compound_element_types.length; h++) {
        var element_type = compound_element_types[h];
        var compound_type = element_type.type;
        var compound_element_id = row_id + ("_col_" + h);
        if (!element_type.is_topic1) {
            var compound_element_html = "<td><input type=\"text\"" + createHTMLParamsEmpty(compound_element_id) + "></input></td>";
            compound_row.append($(compound_element_html));
            fbSuggestMulti(compound_element_id, compound_type, "Create new topic.");
        } else {
        }
    }
}


function createPropertyRow_MixedElement(element_structure) {
    var s = "<tr>";
    var topic1_property_name = element_structure.topic1_html_property_name;
    s += "<th>" + topic1_property_name + "</th>";
    var topic2_elements = element_structure.topic2;
    for (var i = 0; i < topic2_elements.length; i++) {
        var topic2_element = topic2_elements[i];
        if (topic2_element.element_type == "compound") {
            s += "<td><table><tr>";
            var compound_elements = topic2_element.elements;
            for (var j = 0; j < compound_elements.length; j++) {
                var compound_element = compound_elements[j];
                if (!compound_element.is_topic1) {
                    s += "<th>" + compound_element.html_property_name + "</th>";
                } else {
                }
            }
            s += "</tr></table></td>";
        } else {
        }
    }
    s += "</tr>";
    return s;
}


function submitMixedElement(html_id, data, parent_element) {
    var post_command = "/topic_info/write_mixed/";
    var parent_name = data.topic_name;
    var parent_id = data.topic_id;
    var parent_type = data.topic_type;
    var current_vals = data.current_vals;
    var element_structure = data.element_structure;
    var structure_topic2s = element_structure.topic2;
    var parent_property = element_structure.parent_property;
    var topic1_type = element_structure.topic1_type;
    var vals_to_add = new Array;
    var vals_to_remove = new Array;
    var more_primary_elements = true;
    var row_index = 0;
    while (more_primary_elements) {
        var row_id = html_id + ("_row_" + row_index);
        var row = $("#" + row_id);
        var current_primary = null;
        if (current_vals.length > row_index) {
            current_primary = current_vals[row_index];
        }
        if (row.length == 0) {
            more_primary_elements = false;
        } else {
            var primary_id = row_id + "_primary";
            var primary_html = $("#" + primary_id);
            var primary = getElementParameters_html(primary_html);
            var primary_object = null;
            primary_object = new Object;
            primary_object.type = "link";
            primary_object.topic1 = new Object;
            primary_object.topic1.guid = parent_id;
            primary_object.topic2 = new Array;
            primary_object.topic2[0] = primary;
            primary_object.topic2[0].elements_to_add = new Array;
            primary_object.topic2[0].topic1_property = parent_property;
            primary_object.topic2[0].type = element_structure.topic1_type;
            primary_object.topic2[0].force_create = "false";
            var add_primary = false;
            if (primary.name.length > 0) {
                var remove_primary = false;
                if (current_primary != null) {
                    if (!current_primary.guid == primary.guid) {
                        remove_primary = true;
                        add_primary = true;
                    }
                } else if (primary.name.length > 0) {
                    add_primary = true;
                }
                if (remove_primary) {
                    var val_to_remove = new Object;
                    val_to_remove.type = "unlink";
                    val_to_remove.topic1 = new Object;
                    val_to_remove.topic1.guid = parent_id;
                    val_to_remove.topic2 = new Array;
                    val_to_remove.topic2[0] = new Object;
                    val_to_remove.topic2[0].topic1_property = parent_property;
                    val_to_remove.topic2[0].type = element_structure.topic1_type;
                    val_to_remove.topic2[0].elements_to_add = new Array;
                    val_to_remove.topic2[0].force_create = "false";
                    vals_to_remove.push(val_to_remove);
                }
                if (add_primary) {
                    vals_to_add.push(primary_object);
                }
                var more_cols = true;
                var col_index = 0;
                while (more_cols) {
                    var col_id = row_id + ("_col_" + col_index);
                    var col_element = $("#" + col_id);
                    if (col_element.length == 0) {
                        more_cols = false;
                    } else {
                        var structure_topic2 = structure_topic2s[col_index];
                        var e_type = structure_topic2.element_type;
                        var e_topic1_property = structure_topic2.topic1_property;
                        var primary_property = structure_topic2.topic1_property;
                        if (e_type == "compound") {
                            retrieveMixedCompoundElements(col_id, current_primary, primary_property, vals_to_add, vals_to_remove, primary_object, add_primary, e_topic1_property, structure_topic2);
                        }
                    }
                    col_index++;
                }
            }
        }
        row_index++;
    }
    if (vals_to_add.length > 0 || vals_to_remove.length > 0) {
        var transmit_data = new Object;
        transmit_data.vals_to_add = JSON.stringify(vals_to_add);
        transmit_data.vals_to_remove = JSON.stringify(vals_to_remove);
        $.ajax({type: "POST", url: post_command + parent_id + ("/"), data: transmit_data, success: function (m) {}, error: function (m) {}, dataType: "text", cache: false});
    }
}


function retrieveMixedCompoundElements(col_id, current_primary, primary_property, vals_to_add, vals_to_remove, primary, add_primary, e_topic1_property, structure_topic2) {
    var compound_elements_to_add = new Array;
    var more_comp_rows = true;
    var structure_elements = structure_topic2.elements;
    var topic2_type = structure_topic2.type;
    var new_compound_object = null;
    var comp_row_index = 0;
    var add_comp_row_index = 0;
    for (var z = 0; more_comp_rows; z++) {
        var comp_id = col_id + ("_row_" + comp_row_index);
        var comp_row = $("#" + comp_id);
        if (comp_row.length == 0) {
            more_comp_rows = false;
        } else {
            var add_compound_row = false;
            var comp_current_row = null;
            var add_new_compound_row = false;
            var compound_row = getElementParameters_html(comp_row);
            var cr_create_new = "" + compound_row.create_new;
            if (cr_create_new.toLowerCase() == "true") {
                new_compound_object = new Object;
                new_compound_object.type = "link";
                new_compound_object.topic1 = new Object;
                new_compound_object.topic1.guid = primary.topic1.guid;
                new_compound_object.topic2 = new Array;
                var new_compound_index = new_compound_object.topic2.length;
                new_compound_object.topic2[new_compound_index] = compound_row;
                new_compound_object.topic2[new_compound_index].type = topic2_type;
                new_compound_object.topic2[new_compound_index].topic1_property = structure_topic2.topic1_property;
                new_compound_object.topic2[new_compound_index].elements_to_add = new Array;
                new_compound_object.topic2[new_compound_index].force_create = "true";
                add_new_compound_row = true;
            }
            if (add_new_compound_row) {
                comp_current_row = [];
            } else {
                comp_current_row = current_primary[primary_property].length > comp_row_index ? current_primary[primary_property][comp_row_index] : null;
            }
            var e_structs = structure_topic2.elements;
            var add_element_index = 0;
            var val_to_add = new Object;
            val_to_add.type = "link";
            val_to_add.topic1 = new Object;
            val_to_add.topic1.guid = compound_row.guid;
            val_to_add.topic2 = new Array;
            for (var i = 0; i < e_structs.length; i++) {
                var structure_element = structure_elements[i];
                var comp_element_topic_type = structure_element.type;
                var e = e_structs[i];
                var e_property = e.topic1_property;
                var add_element = false;
                var remove_element = false;
                var comp_element_id = comp_id + ("_col_" + i);
                var comp_element = $("#" + comp_element_id);
                var current_comp_element_guid = null;
                var compound_element = null;
                if (!e.is_topic1) {
                    if (comp_element.length > 0 &&
                        comp_element.val().length > 0) {
                        compound_element = getElementParameters_html(comp_element);
                        if (!(add_primary || add_new_compound_row)) {
                            var current_comp_element = comp_current_row[e_property];
                            if (current_comp_element == null) {
                                add_element = true;
                            } else {
                                if (!(current_comp_element.guid == comp_element.attr("topic_guid"))) {
                                    current_comp_element_guid = current_comp_element.guid;
                                    remove_element = true;
                                    add_element = true;
                                }
                            }
                        } else {
                            add_element = true;
                        }
                    }
                } else {
                    if (add_primary) {
                        compound_element = compound_row;
                    } else if (add_new_compound_row) {
                        compound_element = getElementParameters_object(current_primary);
                        add_element = true;
                    }
                }
                if (add_element) {
                    val_to_add.topic2[add_element_index] = compound_element;
                    val_to_add.topic2[add_element_index].topic1_property = structure_element.topic1_property_full;
                    val_to_add.topic2[add_element_index].type = comp_element_topic_type;
                    val_to_add.topic2[add_element_index].elements_to_add = new Array;
                    val_to_add.topic2[add_element_index].force_create = "false";
                    add_element_index++;
                }
                if (remove_element) {
                    var remove_element_index = 0;
                    var val_to_remove = new Object;
                    val_to_remove.type = "unlink";
                    val_to_remove.topic1 = new Object;
                    val_to_remove.topic1.guid = compound_row.guid;
                    val_to_remove.topic2 = new Object;
                    val_to_remove.topic2.guid = current_comp_element_guid;
                    val_to_remove.topic2.topic1_property = structure_element.topic1_property_full;
                    val_to_remove.topic2.type = comp_element_topic_type;
                    vals_to_remove.push(val_to_remove);
                }
            }
            if (add_new_compound_row) {
                var new_compound_topic2 = new_compound_object.topic2;
                new_compound_topic2[new_compound_index].elements_to_add.push(val_to_add);
            }
            if (val_to_add.topic2.length > 0) {
                if (new_compound_object != null) {
                    add_compound_row = true;
                } else {
                    vals_to_add.push(val_to_add);
                }
            }
            if (add_primary && add_compound_row) {
                primary.topic2[0].elements_to_add.push(new_compound_object);
            } else if (add_compound_row) {
                vals_to_add.push(new_compound_object);
            }
        }
        comp_row_index++;
    }
}


function getElementParameters_html(html_element) {
    var element = new Object;
    element.guid = html_element.attr("topic_guid");
    element.id = html_element.attr("topic_id");
    element.type = html_element.attr("topic_type");
    element.name = html_element.attr("topic_name");
    element.create_new = html_element.attr("create_new");
    element.elements_to_add = new Array;
    return element;
}


function getElementParameters_object(val) {
    var element = new Object;
    element.guid = val.guid;
    element.id = val.id;
    element.type = val.type;
    element.name = val.name;
    element.create_new = "false";
    element.elements_to_add = new Array;
    return element;
}


function createHTMLParams(html_id, topic_guid, topic_id, topic_name, topic_type, create_new) {
    var s = " ";
    s += "value=\"" + topic_name + "\"";
    s += "id=\"" + html_id + "\"";
    s += "topic_guid=\"" + topic_guid + "\"";
    s += "topic_id=\"" + topic_id + "\"";
    s += "topic_name=\"" + topic_name + "\"";
    s += "topic_type=\"" + topic_type + "\"";
    s += "create_new=\"" + create_new + "\"";
    return s;
}


function createHTMLParamsEmpty(html_id) {
    return createHTMLParams(html_id, "", "", "", "", true);
}


function onCancelMixed(id, not_editing_html) {
    if ($(this).length > 0) {
        $("#" + id).html(edit_html);
        $("#span_" + id).toggle();
        $("#form_" + id).toggle();
        return false;
    }
}


function fbSuggestMultiRow(id, vals, property_type) {
    for (var a = 0; a < vals.length; a++) {
        var id_full = id + ("_" + a);
        fbSuggestMulti(id_full, property_type, "Create new topic");
    }
}


function fbSuggestMulti(id_full, property_type, suggestNewText) {
    var createType = property_type;
    var options2 = {soft: true, suggest_new: suggestNewText, ac_param: {type: property_type}};
    $("#" + id_full).freebaseSuggest(options2).bind("fb-select", function (e, data) {$(this).attr("create_new", "false");$(this).attr("guid", data.id);$(this).attr("topic_guid", data.id);$(this).attr("topic_name", data.id);$(this).attr("value", data.name);$("#" + id_full).attr("data_val", data.name);}).bind("fb-select-new", function (e, data) {$("#" + id_full).attr("create_new", "true");$("#" + id_full).attr("guid", "n/a");$("#" + id_full).attr("topic_guid", "n/a");$("#" + id_full).attr("topic_name", $("#" + id_full).val());});
    $("#" + id_full).blur(function () {var guid = $("#" + id_full).attr("data_val");if (guid == "") {$("#tooltip" + id_full).show();} else {$("#" + id_full).attr("data_val", "");}});
    $("#" + id_full).focus(function () {$("#tooltip" + id_full).hide();});
}


function sec_element_html(id, value_name, current_val) {
    var s = "<table>";
    s += "<tr>";
    s += "<td>" + value_name + ":</td>";
    s += "<td><input type=\"text\" name=\"\" value=\"" + current_val + "\" id=\"secID_" + id + "\"></input></td>";
    s += "</tr>";
    s += "</table>";
    return s;
}


function submit_sec_element(value, html_id, topic_name, parent_topic_id, properties) {
    var postCommand = "/topic_info/write_compound/";
    var topic1_vals = Object();
    topic1_vals.data = Array();
    topic1_vals.type = compoundPropertyType;
    var topic2_vals = Object();
    topic2_vals.data = Array();
    var topic1_index = topic1_vals.data.length;
    var topic2_index = topic2_vals.data.length;
    topic1_vals.data[topic1_index] = Object();
    topic1_vals.data[topic1_index].id = topic1_id;
    topic1_vals.data[topic1_index].property_name = propertyNames[j];
    topic1_vals.data[topic1_index].property_type = propertyTypes[j];
    topic2_vals.data[topic2_index] = Object();
    topic2_vals.data[topic2_index].val = topic2_val;
    topic2_vals.data[topic2_index].id = topic2_id;
    topic2_vals.data[topic2_index].row_index = i;
    topic2_vals.data[topic2_index].create_new = element.attr("create_new");
    topic2_vals.data[topic2_index].create_type = "\"" + propertyTypes[j] + "\"";
    var data = Object();
    objects.parent_topic_id = parent_topic_id;
    objects.id_rep = id;
    objects.parent_property = compoundProperty;
    objects.topic1_vals = JSON.stringify(topic1_vals);
    objects.topic2_vals = JSON.stringify(topic2_vals);
    $.ajax({type: "POST", url: postCommand + topic_name + ("/"), data: data, success: function (m) {}, error: function (m) {}, dataType: "text", cache: false});
}


function createSyncButton(topic_name) {
    var syncB = "<BUTTON TYPE=SUBMIT HEIGHT=97 WIDTH=350 ALT=\"Starflower\" ALIGN=\"ABSMIDDLE\"> <STRONG>Return to " + topic_name + "</STRONG></BUTTON>";
    if ($("#edit_sync").children().length == 0) {
        $("#edit_sync").append($(syncB)).click(function (e) {location.href = "";});
    }
}


function isPrimativeType(type) {
    if (type == "/type/text") {
        return true;
    } else if (type == "/type/uri") {
        return true;
    } else if (type == "/type/float") {
        return true;
    }
    return false;
}


function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(s);
}


function createWebPage_edit(html_id, topic_name, topic_type, topic_id, current_vals, domain_used, url_read) {
    var propertyNames = ["uri", "description"];
    var useSuggest = [false, false];
    var propertyTypes = ["/type/uri", "/type/text"];
    var compoundPropertyType = "\"/common/webpage\"";
    var compoundProperty = "/common/topic/webpage";
    var webpages_options = {url_read: url_read, current_vals_q: "{\"query\":[{" + "\"/common/topic/webpage\":[{\"*\":null,\"optional\":true}]," + "\"type\":\"/business/company\"," + "\"id\" : \"" + topic_id + "\"" + "}]}", topicName: topic_name, current_vals: current_vals, propertyNames: propertyNames, propertyTypes: propertyTypes, topic_type: topic_type, topic_id: topic_id, compoundPropertyType: compoundPropertyType, compoundProperty: compoundProperty, useSuggest: useSuggest};
    compoundElement(html_id, webpages_options, domain_used);
}


function createHeadquarters_edit(html_id, topic_name, topic_type, topic_id, current_vals, domain_used, url_read, flag) {
    var propertyNames = ["street_address", "citytown", "state_province_region", "postal_code"];
    var useSuggest = [false, true, true, true];
    var propertyTypes = ["/type/text", "/location/citytown", "/location/administrative_division", "/location/postal_code"];
    var compoundPropertyType = "\"/location/mailing_address\"";
    var compoundProperty = "/business/company/headquarters";
    var hq_options = {url_read: url_read, current_vals_q: "{\"query\":[{" + "\"/business/company/headquarters\":[{\"optional\":true," + "\"*\":[]," + "\"citytown\" : {\"optional\":true,\"id\" : null,\"guid\":null,\"name\" : null}," + "\"state_province_region\":{\"optional\":true,\"id\" : null,\"guid\":null,\"name\" : null}," + "\"street_address\":[]," + "\"postal_code\":{\"optional\":true,\"id\" : null,\"guid\":null, \"name\" : null}" + "}]," + "\"type\":\"/business/company\"," + "\"id\" : \"" + topic_id + "\"" + "}]}", topicName: topic_name, current_vals: current_vals, propertyNames: propertyNames, propertyTypes: propertyTypes, type: topic_type, topic_id: topic_id, compoundPropertyType: compoundPropertyType, compoundProperty: compoundProperty, useSuggest: useSuggest};
    if (flag) {
        compoundElement(html_id, hq_options, domain_used, flag);
    } else {
        compoundElement(html_id, hq_options, domain_used);
    }
}


function createDrugPipeline(html_id, biov_domain, topic_name, topic_type, topic_id, current_vals) {
    var element_structure = {topic1_type: "[\"" + biov_domain + "product\",\"" + biov_domain + "bv_therapeutic\"]", topic1_html_property_name: "Therapeutic", button_add_string: "Add New Therapeutic", parent_property: biov_domain + "science_or_technology_company/products", topic2: [{type: "[\"" + biov_domain + "indication\"]", topic1_property: biov_domain + "bv_therapeutic/indication_or_disease", element_type: "compound", button_add_string: "Add Indication", elements: [{topic1_property: "therapeutic", topic1_property_full: biov_domain + "indication/therapeutic", type: "[\"" + biov_domain + "bv_therapeutic\"]", is_topic1: true, html_property_name: ""}, {topic1_property: "disease", topic1_property_full: biov_domain + "indication/disease", type: "[\"" + biov_domain + "bv_medical_condition\"]", is_topic1: false, html_property_name: "Medical Condition"}, {topic1_property: "phase_of_development", topic1_property_full: biov_domain + "indication/phase_of_development", type: "[\"" + biov_domain + "bv_phase_of_development\"]", is_topic1: false, html_property_name: "Phase of Development"}]}]};
    var therapeutic_pipeline_current_vals = current_vals;
    var therapeutic_pipeline_options = {edit_blurb: "drug pipeline", topic_name: topic_name, current_vals: therapeutic_pipeline_current_vals, topic_type: topic_type, topic_id: topic_id, element_structure: element_structure};
    mixedElement(html_id, therapeutic_pipeline_options);
}
